package com.ejoysoft.wlanyz.business;

import com.ejoysoft.auth.MD5;
import com.ejoysoft.common.*;
import com.ejoysoft.common.exception.UserUnitIdException;
import com.ejoysoft.wlanyz.system.Unit;
import com.ejoysoft.wlanyz.system.User;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.jfree.ui.Size2D;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.HashMap;
import java.util.Date;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;

public class Testtemplate{
	private Globa globa;
    private DbConnect db;


    public Testtemplate() {
    }

    public Testtemplate(Globa globa) {
        this.globa = globa;
        db = globa.db;
    }

    public Testtemplate(Globa globa, boolean b) {
        this.globa = globa;
        db = globa.db;
        if (b) globa.setDynamicProperty(this);
    }
    String strTableName1="WLAN_TASK_PROJECTS";
    String strTableName = "WLAN_TASK_TEMPLATES";
    
    //记录集转化为对象
    public Testtemplate load (ResultSet rs,boolean isView){
    	Testtemplate smLoad = new Testtemplate();
		try {
			smLoad.setStrId(rs.getString("strId"));
			smLoad.setStrTemplateName(rs.getString("strTemplateName"));
			smLoad.setStrProjectsId(rs.getString("strProjectsId"));
		} catch (Exception e){
			e.printStackTrace();
		}
		return smLoad;
	}
  

      public Vector<Testtemplate> list(String where,int startRow, int rowCount) {
          Vector<Testtemplate> beans = new Vector<Testtemplate>();
          String where2 = " where 1=1 ";
          //========================================= 
          if(where!=null && !where.replaceAll(" ","").toLowerCase().equals("where1=1orderbystrprojectname"))
          {
        	   List<String> list = returnProId(where);
        	   where2 += "and ( 1=2"; 
	       	   
               for (int i = 0; i < list.size(); i++) {
     			where2 += " or strProjectsId like'%"+list.get(i)+"%'"; 
               }
	       		 where2 +=")";
          }
          //===================================
          try {
        	  String sql= "select *  from "+ strTableName+where2;
              System.out.println("slq:"+sql);
              Statement s = db.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
              if (startRow != 0 && rowCount != 0)
                  s.setMaxRows((startRow + rowCount) - 1);
              ResultSet rs = s.executeQuery(sql);
              if (rs != null && rs.next()) {
                  if (startRow != 0 && rowCount != 0)
                      rs.absolute(startRow);
                  do {
                  	Testtemplate theBean = new Testtemplate();
                      theBean = load(rs, false);
                      beans.addElement(theBean);
                      //System.err.println(rs.getString(3)+startRow+":"+rowCount);
                  } while (rs.next());
              }
              rs.close();
              s.close();
          } catch (Exception ee) {
              ee.printStackTrace();
          }
          return beans;
      }
      
      public Testtemplate load1 (ResultSet rs,boolean isView){
      	Testtemplate smLoad = new Testtemplate();
  		try {
  			smLoad.setStrId(rs.getString("strId"));
  			smLoad.setStrTemplateName(rs.getString("strTemplateName"));
  			smLoad.setStrProjectsId(returnProNames(rs.getString("strProjectsId")));
  		} catch (Exception e){
  			e.printStackTrace();
  		}
  		return smLoad;
  	}
    

        public Vector<Testtemplate> list1(String where,int startRow, int rowCount) {
            Vector<Testtemplate> beans = new Vector<Testtemplate>();
            String where2 = " where 1=1 ";
            //========================================= 
            if(where!=null && !where.replaceAll(" ","").toLowerCase().equals("where1=1orderbystrprojectname"))
            {
          	   List<String> list = returnProId(where);
          	   where2 += "and ( 1=2"; 
  	       	   
                 for (int i = 0; i < list.size(); i++) {
       			where2 += " or strProjectsId like'%"+list.get(i)+"%'"; 
                 }
  	       		 where2 +=")";
            }
            //===================================
            try {
          	  String sql= "select *  from "+ strTableName+where2;
                //System.out.println("slq:"+sql);
                Statement s = db.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                if (startRow != 0 && rowCount != 0)
                    s.setMaxRows((startRow + rowCount) - 1);
                ResultSet rs = s.executeQuery(sql);
                if (rs != null && rs.next()) {
                    if (startRow != 0 && rowCount != 0)
                        rs.absolute(startRow);
                    do {
                    	Testtemplate theBean = new Testtemplate();
                        theBean = load1(rs, false);
                        beans.addElement(theBean);
                        //System.err.println(rs.getString(3)+startRow+":"+rowCount);
                    } while (rs.next());
                }
                rs.close();
                s.close();
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            return beans;
        }
        
//用于查找任务类型
        public Vector<Testtemplate> listTask() {
            Vector<Testtemplate> beans = new Vector<Testtemplate>();
            try {
          	  String sql= "select distinct(strTemplateName)  from "+ strTableName+"";
                Statement s = db.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
               
                ResultSet rs = s.executeQuery(sql);
                if (rs != null && rs.next()) {
                    do {
                    	Testtemplate theBean = new Testtemplate();
                        theBean = loadTask(rs, false);
                        beans.addElement(theBean);
                    } while (rs.next());
                }
                rs.close();
                s.close();
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            return beans;
        }
        public Testtemplate loadTask(ResultSet rs,boolean isView){
          	Testtemplate smLoad = new Testtemplate();
      		try {
      			smLoad.setStrTemplateName(rs.getString("strTemplateName"));
      		} catch (Exception e){
      			e.printStackTrace();
      		}
      		return smLoad;
      	}
      
      //列表记录集
      public int getCount(String where) {
          int count = 0;
          String where2 = " where 1=1 ";
          //=========================================
          if(where!=null && !where.replaceAll(" ","").toLowerCase().equals("where1=1"))
          {
        	   List<String> list = returnProId(where);
        	   where2 += "and ( 1=2 ";
	       	   if(list.size() >=1){
	       		  
	       	   }
              for (int i = 0; i < list.size(); i++) {
    			where2 += " or strProjectsId like'%"+list.get(i)+"%' ";
    			//System.err.println("==============================="+list.get(i));
    		  }
	       		 where2 +=")";
          }
          //========================================
          try {
        	  String sql = "select count(strId) from "+strTableName+ where2;
             
              ResultSet rs = db.executeQuery(sql);
              if (rs.next())
                  count = rs.getInt(1);   
              rs.close();
              return count;
             
          } catch (Exception e) {
              e.printStackTrace();
              System.out.println(e);           
              return count;
          }
      }
      public Testtemplate show(String where) {
          try {
              String strSql = "select * from  " + strTableName + "  ".concat(where);
              ResultSet rs = db.executeQuery(strSql);
              if (rs != null && rs.next())
                  return load(rs, true);
              else
                  return null;
          } catch (Exception e) {
              return null;
          }
      }
      
     public List<String> returnProId(String where) {
    	  List<String> list = new ArrayList<String>();
          try {
              String strSql = "select * from  " + strTableName1 + " ".concat(where);
              ResultSet rs = db.executeQuery(strSql);
              if (rs != null){
            	 while (rs.next()) {
                     list.add(rs.getString("strProjectId"));
				}
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
          return list;
      }
     
     public String returnProNames(String proids) {
   	  String names = "",tempIds="";
   	  if(proids!=null){
   		  String str[] = proids.split(",");
   		  if(str!=null){
   			  for (int i = 0; i < str.length-1; i++) {
				String temp = str[i];
				tempIds += "'"+temp+"',";
			  }
   			  tempIds += "'"+str[str.length-1]+"'";
   		  }
   		  
   		try {
            String strSql = "select * from  " + strTableName1 + " where strProjectId in("+tempIds+")";
           
            ResultSet rs = db.executeQuery(strSql);
            if (rs != null){
	          	 while (rs.next()) {
	          		if(rs.getString("strProjectName")!=null)
	                   names += rs.getString("strProjectName")+",";
				 }
	      	     if (names!=null && names.length()>=1) {
					names = names.substring(0, names.length()-1);
				 }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
   	  }
         
         return names;
     }
     
     
     public String returnProids(String projectnames) {
      	  String ids = "",tempNames="";
      	  if(projectnames!=null){
      		  String str[] = projectnames.split(",");
      		  if(str!=null){
      			  for (int i = 0; i < str.length-1; i++) {
   				String temp = str[i];
   				tempNames += "'"+temp+"',";
   			  }
      			  tempNames += "'"+str[str.length-1]+"'";
      		  }
      		try {
               String strSql = "select strProjectId from  " + strTableName1 + " where strProjectName in("+tempNames+")";
               ResultSet rs = db.executeQuery(strSql);
               if (rs != null){
   	          	 while (rs.next()) {
   	          		if(rs.getString("strProjectId")!=null)
   	                   ids += rs.getString("strProjectId")+",";
   	          	 }
   	      	     if (ids!=null && ids.length()>=1) {
   					ids = ids.substring(0, ids.length()-1);
   					
   				 }
               }
           } catch (Exception e) {
               e.printStackTrace();
           }
      	  }
            
            return ids;
        }
     /* public String returnProId(String where) {
          try {
              String strSql = "select * from  " + strTableName1 + " ".concat(where);
              ResultSet rs = db.executeQuery(strSql);
              if (rs != null && rs.next()){
            	 while (rs.next()) {
                     String list = rs.getString("strProjectId");
				}
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
          return list;
      }*/
     public boolean delete(String where) {
         try {
             String sql = "DELETE FROM " + strTableName + "  ".concat(where);
             db.executeUpdate(sql);
             Globa.logger0("删除任务信息", globa.loginName, globa.loginIp, sql, "任务管理", globa.unitCode);
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }
     
     public boolean add(String strTemplateName,String strProjectsName){ 
         String strSql = "";
         strId = UID.getID();
         strProjectsId = returnProids(strProjectsName);
         try {
         	//把用户信息写入数据库
             strSql = "INSERT INTO " + strTableName + "  (strId, strTemplateName, strProjectsId, strOperator, dtCreatDate) VALUES (?,?,?,?,to_date(?,'yyyy-MM-dd hh24:mi:ss'))";
            
             db.prepareStatement(strSql);
             db.setString(1, strId);
             db.setString(2, strTemplateName);
             db.setString(3, strProjectsId);   
             db.setString(4, globa.loginName);
             db.setString(5, Format.getDateTime());
    
             if (db.executeUpdate() > 0) {
                 Globa.logger0("增加测试模板信息", globa.loginName, globa.loginIp, strSql, "任务管理", globa.userSession.getStrDepart());
                 
                 return true;
             } else
                 return false;
         } catch (Exception e) {
             System.out.println("增加用户信息时出错！！");
             e.printStackTrace();
             return false;
         }
     }
     
     public boolean update(String strId,String strTemplateName,String strProjectsName) {
    	     strProjectsId = returnProids(strProjectsName);
         try {
             String strSql = "UPDATE  " + strTableName + "  SET  strTemplateName = ?, strProjectsId = ?, strOperator = ?, dtCreatDate = to_date(?,'yyyy-MM-dd hh24:mi:ss')  WHERE strId=? ";
             db.prepareStatement(strSql);
             db.setString(1, strTemplateName);
             db.setString(2, strProjectsId);
             db.setString(3, globa.loginName);
             db.setString(4, Format.getDateTime());
             db.setString(5, strId);
             db.executeUpdate();
             Globa.logger0("修改测试模板信息", globa.loginName, globa.loginIp, strSql, "用户管理", globa.userSession.getStrDepart());
             return true;
         } catch (Exception e) {
             System.out.println("修改用户信息时出错：" + e);
             return false;
         }
     }
     
     
     

    private String strId;//	id号
    private String strTemplateName;
    private String strProjectsId;
    private String strProjectsName;
	private String strOpeartor;
    private String dtCreatTime;
    public String getStrProjectsName() {
		return strProjectsName;
	}

	public void setStrProjectsName(String strProjectsName) {
		this.strProjectsName = strProjectsName;
	}
    
    
    
    
    
    public String getStrTemplateName() {
		return strTemplateName;
	}

	public void setStrTemplateName(String strTemplateName) {
		this.strTemplateName = strTemplateName;
	}

	public String getStrProjectsId() {
		return strProjectsId;
	}

	public void setStrProjectsId(String strProjectsId) {
		this.strProjectsId = strProjectsId;
	}

	public String getStrOpeartor() {
		return strOpeartor;
	}

	public void setStrOpeartor(String strOpeartor) {
		this.strOpeartor = strOpeartor;
	}

	public String getStrId() {
		return strId;
	}

	public void setStrId(String strId) {
		this.strId = strId;
	}

	public String getDtCreatTime() {
		return dtCreatTime;
	}

	public void setDtCreatTime(String dtCreatTime) {
		this.dtCreatTime = dtCreatTime;
	}

}